<?php

namespace app\admin\controller\jskmsg;

use app\admin\library\Auth;
use app\api\model\RecycleOrderItemModel;
use app\api\model\RecycleOrderModel;
use app\api\model\UserModel;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 回收订单管理
 *
 * @icon fa fa-circle-o
 */
class Recycleorder extends Backend
{

    /**
     * Recycleorder模型对象
     * @var \app\admin\model\jskmsg\Recycleorder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jskmsg\Recycleorder;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['user','role','cancel'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$item){
            $order_item_list = RecycleOrderItemModel::where('order_id',$item['id'])->select();
            if($order_item_list){
                $category_name = '';
                foreach ($order_item_list as $vv){
                    $category_name .= $vv['category_name'].',';
                }
                $item['category_name']  = trim($category_name,',');
            }else{
                $item['category_name'] = '';
            }
            if($item['actual_price']==0){
                $item['actual_price'] = '';//实际价格
            }
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['city'] = $row['province'].'/'.$row['city'].'/'.$row['district'];//省市区 组装
            $order_item_list = RecycleOrderItemModel::where('order_id',$row['id'])->select();
            if($order_item_list){
                $category_name = '';
                foreach ($order_item_list as $vv){
                    $category_name .= $vv['category_name'].',';
                }
                $row['category_name']  = trim($category_name,',');
            }else{
                $row['category_name'] = '';
            }
            if(empty($row['complete_time'])){
                $row['complete_time'] = '';
            }else{
                $row['complete_time'] = date('Y-m-d H:i:s',$row['complete_time']);
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['status']==4){
            $this->error('该订单已经取消成功，无法操作了');
        }
        if($row['status'] == 1 && $params['status']==1){
            unset($params['role_id']);
        }
        if($params['status']==3 && $row['status']==1){
            $this->error('该订单还未接单，请先接单在操作！');
        }
        if($params['status']==4 && $row['status']==3){
            $this->error('该订单已经完成了，无法取消！');
        }
        if($params['status']==2){
            //接单
            $params['take_time'] = time();//接单时间
            //接单员角色id
            if(isset($params['role_id'])){
                $user = UserModel::find($params['role_id']);
                $params['role_name'] = $user->nickname;//接单员角色昵称
            }
        }
        if($params['status']==3){
            //订单完成
            unset($params['role_id']);
            $params['complete_time'] = time();//确认完成时间
        }
//        if($row['status'] ==3 && $params['status']==4){
//            //订单取消
//            unset($params['role_id']);
//            $params['admin_id'] = $this->auth->id;//后台操作员id
//            $params['cancel_time'] = time();//取消时间
//        }
        if ($params['status']==4){
            //订单取消
            unset($params['role_id']);
            $params['admin_id'] = $this->auth->id;//后台操作员id
            $params['cancel_time'] = time();//确认完成时间
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            unset($params['category_name']);//去掉分类
            if(empty($params['city'])) {
                $params['province'] = '';//省
                $params['city'] = '';//市
                $params['district'] = '';//区
            }else{
                $citys = explode('/',$params['city']);//福建省/厦门市/思明区  拆分
                $params['province'] = isset($citys[0])?$citys[0]:'';//省
                $params['city'] = isset($citys[1])?$citys[1]:'';//市
                $params['district'] = isset($citys[2])?$citys[2]:'';//区
            }

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //回收价格
    public function recycleprice($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['status']==1){
            $this->error('该订单不是已接单状态，无法操作！');
        }
        if($row['status']==3){
            $this->error('该订单已经完成了');
        }
        if($row['status']==4){
            $this->error('该订单已经取消了');
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $admin = $this->auth->getUserInfo();
            $rr = RecycleOrderModel::complete($row['user_id'],$row,$params['actual_price'],$admin['id']);
            if($rr !== true){
                Db::rollback();
                $this->error('操作失败');
            }else{
                $result = $row->allowField(true)->save($params);
                Db::commit();
            }
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
